/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.epos.grogshop;

import cn.ekuma.epos.bean.util.SerivceHelper;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.bean.Place;
import com.openbravo.bean.Service;
import com.openbravo.bean.Serving;
import com.openbravo.bean.sales.Ticket;
import com.openbravo.bean.sales.TicketLine;
import com.openbravo.pos.payment.JPaymentKeyBoardSelectReceipt;
import com.openbravo.pos.payment.JPaymentKeyboardSelectRefund;
import com.openbravo.pos.payment.JPaymentSelect;
import com.openbravo.pos.sales.SaleConfig;
import com.openbravo.pos.sales.TicketsEditor;
import com.openbravo.pos.sales.restaurant.AbstractJTicketsBagRestaurant;
import javax.swing.JComponent;
import java.awt.event.*;
import java.util.Date;
import java.util.UUID;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
/**
 *
 * @author Administrator
 */
public class JTicketsBagGrogShopMapKeyBoard extends AbstractJTicketsBagRestaurant{

   
    public JTicketsBagGrogShopMapKeyBoard(AppView app, TicketsEditor panelticket) {
        super(app,panelticket,SaleConfig.RESTAURANT_PRINT_PLACESTATE_GHOGSHOP);
        m_grogshopmap=new JTicketsBagGhogShopKeyBoard(app, this);
    }

    private JPopupMenu   ghogShopPopupMenu;
    JTicketsBagGhogShopKeyBoard m_grogshopmap;
    private Place selectPlace;
    public static String GHOGSHOP_TABLE_SERVINGS="grog.servings.tableId";


    @Override
    protected ActionListener getPlaceActionListener(Place pl) {
        return new MyActionListener(pl);
    }

    @Override
    public JComponent getComponent() {
        return this;
    }

    @Override
   public  JComponent getBagComponent() {
        return m_grogshopmap;
    }

    private class MyActionListener implements ActionListener {

        public MyActionListener(Place place) {
            m_place = place;
        }
        
        private Place m_place;
        
        @Override
        public void actionPerformed(ActionEvent evt) {
        	
        }
        
/**
        @Override
        public void actionPerformed(ActionEvent evt) {
            selectPlace=m_place;
            if (m_PlaceClipboard == null) {//无原单模式
                if (customerInfo == null) {//1.显示菜单
                   getPopupMenu(m_place).setVisible(true);
                } else { // 2.预订下单
                    receiveCheck(m_place);
                }
            } else {//原单模式
                // check if the sharedticket is the same
                Ticket ticketclip = getTicketInfo(m_PlaceClipboard);

                if (ticketclip == null) {//出现内部逻辑错误，如原单据以变其它对应操作。
                    new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tableempty")).show(getComponent());
                    setPlaceSelect(m_PlaceClipboard,false);
                    m_PlaceClipboard = null;
                    customerInfo = null;
                    printState();
                } else {
                    // tenemos que copiar el ticket del clipboard
                    if (m_PlaceClipboard == m_place) {//原和目标对象相同，不处理
                        // the same button. Canceling.
                        Place placeclip = m_PlaceClipboard;
                        m_PlaceClipboard = null;
                        customerInfo = null;
                        printState();
                        setActivePlace(placeclip, ticketclip);
                    } else if (!m_place.hasPeople()) {//目标无单据，进行移位处理
                        moveCheck(m_place,ticketclip);
                    } else {//目标有单据，进行合并处理
                        mageCheck(m_place,ticketclip);
                    }
                }
            }
      }
  }

   private void emptyCheck(Place m_place){

                    // check if the sharedticket is the same
                    Ticket ticket = getTicketInfo(m_place);

                    // check
                    if (ticket == null && !m_place.hasPeople()) {
                        // Empty table and checked

                        JPlaceRegisterDialog registerDialog= JPlaceRegisterDialog.newJDialog(this,dlCustomers,m_dlSales);
                        if(registerDialog.register(selectPlace, customerInfo)){
                        // table occupied
                        ticket = new Ticket();
                        ticket.setM_sGroupName(m_place.getM_sGroupName());
                        ticket.setCustomer(registerDialog.getCustomer());
                        TicketLine oLine=new TicketLine();
                        oLine.setServings(registerDialog.getServings());
                        oLine.setProperty(GHOGSHOP_TABLE_SERVINGS, m_place.getId());
                        ticket.addLine(oLine);
                        try {
                            dlReceipts.insertSharedTicket(m_place.getId(), ticket);
                        } catch (BasicException e) {
                            new MessageInf(e).show(getComponent()); // Glup. But It was empty.
                        }
                        setPlaceSelect(m_place,true);
                        setActivePlace(m_place, ticket);
                        }
                    } else if (ticket == null  && m_place.hasPeople()) {
                        // The table is now empty
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tableempty")).show(getComponent());
                        setPlaceSelect(m_place,false);

                    } else if (ticket != null && !m_place.hasPeople()) {
                        // The table is now full
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tablefull")).show(getComponent());
                        
                        setPlaceSelect(m_place,true);

                    } else { // both != null
                        // Full table
                        // m_place.setPeople(true); // already true
                        ticket.setM_sGroupName(m_place.getM_sGroupName());
                        setActivePlace(m_place, ticket);
                    }

        }

        private void receiveCheck(Place m_place){
                                // check if the sharedticket is the same
                    Ticket ticket = getTicketInfo(m_place);
                    if (ticket == null) {
                        // receive the customerInfo
                        // table occupied
                        JPlaceRegisterDialog registerDialog= JPlaceRegisterDialog.newJDialog(this,dlCustomers,m_dlSales);
                        if(registerDialog.register(selectPlace, customerInfo)){
                        // table occupied
                        ticket = new Ticket();
                        ticket.setM_sGroupName(m_place.getM_sGroupName());
                        ticket.setCustomer(registerDialog.getCustomer());
                        ticket.setUser(this.m_App.getAppUserView().getUser().getUserInfo());
                        ticket.setLocation(this.m_App.getInventoryLocation());
                        ticket.setDate(new Date());
                        TicketLine oLine=new TicketLine();
                        oLine.setServings(registerDialog.getServings());
                        oLine.setProperty(GHOGSHOP_TABLE_SERVINGS, m_place.getId());
                        ticket.addLine(oLine);

                        try {
                            dlReceipts.insertSharedTicketNoLock(m_place.getId(), ticket);
                        } catch (BasicException e) {
                            new MessageInf(e).show(getComponent()); // Glup. But It was empty.
                        }
                        setPlaceSelect(m_place,true);

                        m_place.setM_sGroupName(null);
                        try {
                            m_dlSales.updatePlace(m_place.getId(), m_place);
                        } catch (BasicException e) {
                            new MessageInf(e).show(getComponent()); // Glup. But It was empty.
                        }
                        m_PlaceClipboard = null;
                        customerInfo = null;

                        setActivePlace(m_place, ticket);
                        }
                    } else {
                        // TODO: msg: The table is now full
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tablefull")).show(getComponent());
                        JButton selectBut=placeButtonMap.get(m_place);
                        setPlaceSelect(m_place,true);
                        selectBut.setEnabled(false);

                    }
        }

        private void moveCheck(Place m_place,Ticket ticketclip){
            // Moving the receipt to an empty table
                        Ticket ticket = getTicketInfo(m_place);

                        if (ticket == null) {
                            try {
                                m_place.setM_sGroupName(m_PlaceClipboard.getM_sGroupName());

                                Serving pServings=getPlaceServings(m_place, ticketclip);
                                pServings.setReturnData(new Date());
                                Serving newServings=getNewServings(m_place);
                                newServings.setRantPrice(pServings.getRantPrice());
                                pServings.setRantPrice(0);
                                TicketLine oLine=new TicketLine();
                                oLine.setServings(newServings);
                                oLine.setProperty(GHOGSHOP_TABLE_SERVINGS, m_place.getId());
                                ticket.addLine(oLine);

                                dlReceipts.insertSharedTicketNoLock(m_place.getId(), ticketclip);

                                setPlaceSelect(m_place,true);
                                dlReceipts.deleteSharedTicket(m_PlaceClipboard.getId());

                                setPlaceSelect(m_PlaceClipboard,false);
                                m_PlaceClipboard.setM_sGroupName(null);
                                
                                m_dlSales.updatePlace(m_place.getId(), m_place);
                                m_dlSales.updatePlace(m_PlaceClipboard.getId(), m_PlaceClipboard);
                            } catch (BasicException e) {
                                new MessageInf(e).show(getComponent()); // Glup. But It was empty.
                            }

                            m_PlaceClipboard = null;
                            customerInfo = null;
                            printState();

                            // No hace falta preguntar si estaba bloqueado porque ya lo estaba antes
                            // activamos el ticket seleccionado
                            setActivePlace(m_place, ticketclip);
                        } else {//出现内部逻辑错误，如以被其它先占用。
                            // Full table
                            new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tablefull")).show(getComponent());

                            setPlaceSelect(m_PlaceClipboard,true);
                            printState();
                        }
        }

        private Serving getNewServings(Place m_place) throws BasicException{
           Service service = m_dlSales.findService(Service.SERVICETYPE_place, m_place.getId());
           Serving  servings =new Serving(service,0);
           servings.setM_sId(UUID.randomUUID().toString());
           servings.setM_sName(SerivceHelper.printServiceName(service));
           return servings;
        }


        private void mageCheck(Place m_place,Ticket ticketclip){
                                     //加入组判断,不同组之间将不能合并
                        if(m_PlaceClipboard.isGroupPlace()&&m_place.isGroupPlace()&&!m_PlaceClipboard.getM_sGroupName().equalsIgnoreCase(m_place.getM_sGroupName())){
                           new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.twotablegroupdeff")).show(getComponent());
                           return;
                        }

                        // Merge the lines with the receipt of the table
                        Ticket ticket = getTicketInfo(m_place);

                        if (ticket == null) {//出现内部逻辑错误，如原单据以变其它对应操作。
                            // The table is now empty
                            new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tableempty")).show(getComponent());

                            setPlaceSelect(m_place,false);
                        } else {
                            //asks if you want to merge tables
                            if (JOptionPane.showConfirmDialog(getComponent(), AppLocal.getIntString("message.mergetablequestion"), AppLocal.getIntString("message.mergetable"), JOptionPane.YES_NO_OPTION)
                                    == JOptionPane.YES_OPTION){
                                // 合并开始
                             if(m_PlaceClipboard.isGroupPlace()&&!m_place.isGroupPlace()||!m_PlaceClipboard.isGroupPlace()&&m_place.isGroupPlace()){
                                if (JOptionPane.showConfirmDialog(getComponent(), AppLocal.getIntString("message.mergetablegroupquestion"), AppLocal.getIntString("message.mergetable"), JOptionPane.YES_NO_OPTION)
                                    == JOptionPane.YES_OPTION){
                                    Place placeclip = m_PlaceClipboard;
                                    m_PlaceClipboard = null;
                                    customerInfo = null;
                                    printState();
                                    setActivePlace(placeclip, ticketclip);
                                }
                             }else{
                             try {
                                    //ticket.setM_sGroupName(m_PlaceClipboard.getM_sGroupName());
                                    if(m_PlaceClipboard.isGroupPlace()&&!m_place.isGroupPlace()){
                                        m_place.setM_sGroupName(m_PlaceClipboard.getM_sGroupName());
                                        m_PlaceClipboard.setM_sGroupName(null);
                                        m_dlSales.updatePlace(m_PlaceClipboard.getId(), m_PlaceClipboard);
                                        m_dlSales.updatePlace(m_place.getId(), m_place);
                                    }else if(m_PlaceClipboard.isGroupPlace()&&m_place.isGroupPlace()){
                                        m_PlaceClipboard.setM_sGroupName(null);
                                        m_dlSales.updatePlace(m_PlaceClipboard.getId(), m_PlaceClipboard);
                                    }

                                    ticket.setM_sGroupName(m_place.getM_sGroupName());
                                    dlReceipts.deleteSharedTicket(m_PlaceClipboard.getId());

                                    setPlaceSelect(m_PlaceClipboard,false);

                                    if (ticket.getCustomer() == null) {
                                    ticket.setCustomer(ticketclip.getCustomer());
                                    }

                                    Serving pServings=getPlaceServings(m_place, ticketclip);
                                    pServings.setReturnData(new Date());

                                    for(TicketLine line : ticketclip.getLines()) {
                                        ticket.addLine(line);
                                    }

                                    dlReceipts.updateSharedTicket(m_place.getId(), ticket, null);
                                } catch (BasicException e) {
                                    new MessageInf(e).show(getComponent()); // Glup. But It was empty.
                                }

                                m_PlaceClipboard = null;
                                customerInfo = null;
                                printState();

                                setActivePlace(m_place, ticket);
                             }
                            } else {//用户取消，刷新
                                // Cancel merge operations
                                Place placeclip = m_PlaceClipboard;
                                m_PlaceClipboard = null;
                                customerInfo = null;
                                printState();
                                setActivePlace(placeclip, ticketclip);
                          }
             }
             */
  }
/**
  public JPopupMenu getPopupMenu(Place place){
      if(ghogShopPopupMenu==null){
           ghogShopPopupMenu=new JPopupMenu();
      }
      ghogShopPopupMenu.add(new RegisterAction("/com/openbravo/images/yast_security.png","GhogShop.Menu.register"));
      ghogShopPopupMenu.add(new SaleAction("/com/openbravo/images/knotes.png","GhogShop.Menu.pay"));
      ghogShopPopupMenu.add(new MoveOrMergeAction("/com/openbravo/images/redo16.png","GhogShop.Menu。moveOrMerge"));
      ghogShopPopupMenu.add(new ChangeStateAction("/com/openbravo/images/gohome.png","GhogShop.Menu.changeState"));
      ghogShopPopupMenu.add(new DetailAction("/com/openbravo/images/edit.png","GhogShop.Menu.detail"));
      return ghogShopPopupMenu;
  }

  private void payTicket(Place m_place){
                 // check if the sharedticket is the same
                    Ticket ticket = getTicketInfo(m_place);

                    // check
                    if (ticket == null && !m_place.hasPeople()) {
                         // The table is now empty
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.grogtableempty")).show(getComponent());
                    } else if (ticket == null  && m_place.hasPeople()) {
                        // The table is now empty
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tableempty")).show(getComponent());
                        m_place.setPeople(false); // fixed

                    } else if (ticket != null && !m_place.hasPeople()) {
                        // The table is now full
                        new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tablefull")).show(getComponent());
                        
                        setPlaceSelect(m_place,true);
                        m_place.setM_sGroupName(ticket.getM_sGroupName());

                        setActivePlace(m_place, ticket);
                    } else { // both != null
                        // Full table
                        // m_place.setPeople(true); // already true
                        ticket.setM_sGroupName(m_place.getM_sGroupName());
                        setActivePlace(m_place, ticket);
            }
  }

  private void detail(Place m_place){
        Ticket ticket = getTicketInfo(m_place);

       if (ticket == null) {//出现内部逻辑错误，如原单据以变其它对应操作。
                            // The table is now empty
               new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.tableempty")).show(getComponent());
               
               setPlaceSelect(m_place,false);
       } else {
          Serving m_placeServing=getPlaceServings(m_place,ticket);
          JPlaceRegisterDialog registerDialog= JPlaceRegisterDialog.newJDialog(this,dlCustomers,m_dlSales);
          if(registerDialog.detail(m_place, ticket.getCustomer(),m_placeServing)){
                try {
                    dlReceipts.updateSharedTicket(m_place.getId(), ticket, null);
                } catch (BasicException ex) {
                     new MessageInf(ex).show(getComponent()); // Glup. But It was empty.
                }
          }
       }
  }

  private void changeState(Place m_place){

  }

  private Serving getPlaceServings(Place m_place,Ticket placeTicket){
      for(TicketLine l:placeTicket.getLines()){
          if(l.isServiceTicketLine()&&l.getProperty(GHOGSHOP_TABLE_SERVINGS, "").equalsIgnoreCase(m_place.getId()))
              return l.getServings();
      }
      return null;
  }

  //登记
  private class RegisterAction extends AbstractAction {

        public RegisterAction(String icon, String keytext) {
            putValue(Action.SMALL_ICON, new ImageIcon(JTicketsBagGrogShopMapKeyBoard.class.getResource(icon)));
            putValue(Action.NAME, AppLocal.getIntString(keytext));
        }

        public void actionPerformed(ActionEvent evt) {
              emptyCheck(selectPlace);
        }

        @Override
        public boolean isEnabled() {
            return !selectPlace.hasPeople();
        }
    }



    //改变对象状态命令
    private class ChangeStateAction extends AbstractAction {

        public ChangeStateAction(String icon, String keytext) {
            putValue(Action.SMALL_ICON, new ImageIcon(JTicketsBagGrogShopMapKeyBoard.class.getResource(icon)));
            putValue(Action.NAME, AppLocal.getIntString(keytext));
        }

        public void actionPerformed(ActionEvent evt) {
             changeState(selectPlace);
        }

        @Override
        public boolean isEnabled() {
            return !selectPlace.hasPeople();
        }
    }

      //换房/并房
       private class MoveOrMergeAction extends AbstractAction {

        public MoveOrMergeAction(String icon, String keytext) {
            putValue(Action.SMALL_ICON, new ImageIcon(JTicketsBagGrogShopMapKeyBoard.class.getResource(icon)));
            putValue(Action.NAME, AppLocal.getIntString(keytext));
        }

        public void actionPerformed(ActionEvent evt) {
               moveTicket();
        }

        @Override
        public boolean isEnabled() {
            return selectPlace.hasPeople();
        }
    }

       //商品销售
       private class SaleAction extends AbstractAction {

        public SaleAction(String icon, String keytext) {
            putValue(Action.SMALL_ICON, new ImageIcon(JTicketsBagGrogShopMapKeyBoard.class.getResource(icon)));
            putValue(Action.NAME, AppLocal.getIntString(keytext));
        }

        public void actionPerformed(ActionEvent evt) {
            payTicket(selectPlace);
        }

        @Override
        public boolean isEnabled() {
            return selectPlace.hasPeople();
        }
    }

      //显示入住详情
       private class DetailAction extends AbstractAction {

        public DetailAction(String icon, String keytext) {
            putValue(Action.SMALL_ICON, new ImageIcon(JTicketsBagGrogShopMapKeyBoard.class.getResource(icon)));
            putValue(Action.NAME, AppLocal.getIntString(keytext));
        }

        public void actionPerformed(ActionEvent evt) {
            detail(selectPlace);
        }

        @Override
        public boolean isEnabled() {
            return selectPlace.hasPeople();
        }
    }*/

	@Override
	public void selectValidTicket() {
	}

	@Override
	public JPaymentSelect getPaymentdialogreceipt() {
		return  JPaymentKeyBoardSelectReceipt.getDialog(this);
	}

	@Override
	public JPaymentSelect getPaymentdialogrefund() {
		return  JPaymentKeyboardSelectRefund.getDialog(this);
	}
    
}
